package com.xiaofeng.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import com.xiaofeng.dao.idao.BaseSessionDao;
import com.xiaofeng.dao.idao.TransferDao;
import com.xiaofeng.pojo.Page;
import com.xiaofeng.pojo.Transfer;




@Repository("transferDao")
public class TransferDaoImpl extends BaseSessionDao implements TransferDao{


	
	Session session = null;
	@Override
	public void insert(Transfer transfer) throws Exception {
	session = getSession();
	Transaction transaction = session.beginTransaction();
	session.save(transfer);
	transaction.commit();
	session.close();
		
	}
	@Override
	public void delete(Transfer transfer) throws Exception {
		session = getSession();
		Transaction transaction = session.beginTransaction();
		session.delete(transfer);
		transaction.commit();
		session.close();
		
	}
	@Override
	public void update(Transfer transfer) throws Exception {
		session = getSession();
		Transaction transaction = session.beginTransaction();
		session.saveOrUpdate(transfer);
		transaction.commit();
		session.close();
		
	}
	@Override
	public Transfer findById(int id) throws Exception {
		session = getSession();
		Transaction transaction = session.beginTransaction();
		Transfer transfer = (Transfer) session.createQuery("from Transfer where id = ?")
				.setInteger(0, id)
				.uniqueResult();
		transaction.commit();
		session.close();
		return transfer;
	}
	@Override
	public List<Transfer> findAll(int num,int size) throws Exception {
		session = getSession();
		Transaction transaction = session.beginTransaction();
		List<Transfer> list = session.createQuery("from Transfer")
				.setFirstResult((num - 1)*size)
				.setMaxResults(size).list();
		transaction.commit();
		session.close();
		return list;
	}
	@Override
	public Page<Transfer> findByPageNo(int pageNo) throws Exception {
		Page<Transfer> page = new Page<Transfer>();
		page.setTotalNum(getTotalNum());
		page.setPageNo(pageNo);
		page.setList(findAll(page.getPageNo(), 3));
		return page;
	}
	@Override
	public int getTotalNum() throws Exception {
		session = getSession();
		Transaction transaction = session.beginTransaction();
		
		int a  =( (Long)session.createQuery("SELECT COUNT(*) from Transfer")
				.setCacheable(true)
				.uniqueResult())
				.intValue();
		transaction.commit();
		session.close();
		return a;
	}
	
	
}
